package com.jack.helloworld.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

class DESUtil {

	private static Cipher cipher = null;

	public static String encodeData(String data, String encKey) {
		try {
			SecretKeySpec keySpec = new SecretKeySpec(encKey.getBytes("utf-8"), "DES");
			// 选择 使用 DES 算法， ECB 方式，填充方式为 PKCS5Padding
			cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			// / 初始化
			cipher.init(Cipher.ENCRYPT_MODE, keySpec);
			// 获取 加密 后的字符串
			byte[] encryptedString = cipher.doFinal(data.getBytes("utf-8"));

			return new String(HexUtil.encode(encryptedString));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String decodeData(String data, String encKey) {
		try {
			byte[] deData;
			SecretKeySpec keySpec = new SecretKeySpec(encKey.getBytes("utf-8"), "DES");
			// 选择 使用 DES 算法， ECB 方式，填充方式为 PKCS5Padding
			cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			// / 初始化
			cipher.init(Cipher.DECRYPT_MODE, keySpec);

			deData = cipher.doFinal(HexUtil.decode(data));

			return new String(deData);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		String data = "abcdefg";
		String key = "10V6U510";
		String encodeData = encodeData(data, key);
		System.out.println("encodeData:" + encodeData);
		System.out.println("decodeData:" + decodeData(encodeData, key));

	}

}
